package com.gy.algorithm.carl.linklistexa;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @BelongsProject: javabase
 * @BelongsPackage: com.gy.algorithm.carl.linklistexa
 * @Author: gy
 * @Date: 2024/10/29 10:56
 * @Description:
 */
public class IsPalindrome234 {
    public static boolean isPalindrome(ListNode head) {
        ListNode middle = getMiddle(head);
        ListNode halfStart = reverseList(middle.next);

        ListNode start = head;

        while(start != null && halfStart != null){
            if(start.val != halfStart.val){
                return false;
            }
            start = start.next;
            halfStart = halfStart.next;
        }

        return true;

    }

    private static ListNode reverseList(ListNode middle) {
        ListNode pre = null;
        ListNode cur = middle;

        while (cur != null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }

        return pre;
    }

    private static ListNode getMiddle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    public static boolean isPalindrome1(ListNode head) {
        if(head == null || head.next == null) return true;
        List<Integer> nums = new ArrayList<>();
        int len = 0;
        while (head != null){
            nums.add(head.val);
            head = head.next;
            len ++;
        }

        int left = 0;
        int right = nums.size() - 1;
        while (left < right){
            if(nums.get(left) == nums.get(right)){
                left++;
                right--;
            }else {
                return false;
            }
        }

        return true;

    }
}
